package cn.edu.sjtu.se.dslab.service.achieve;

import cn.edu.sjtu.se.dslab.DAO.IUserDAO;
import cn.edu.sjtu.se.dslab.actionbean.EditUserActionBean;
import cn.edu.sjtu.se.dslab.actionbean.PageBean;
import cn.edu.sjtu.se.dslab.actionbean.UserActionBean;
import cn.edu.sjtu.se.dslab.exception.DBException;
import cn.edu.sjtu.se.dslab.pojo.User;
import cn.edu.sjtu.se.dslab.service.IUserService;
import cn.edu.sjtu.se.dslab.util.Const;
import cn.edu.sjtu.se.dslab.util.Message;
/**
 * UserService<BR>
 * 业务处理实现类
 * 
 */
@SuppressWarnings("unchecked")
public class UserService implements IUserService{

	/**
	 * 系统用户处理类
	 */
	private IUserDAO userDao;
	


	public IUserDAO getUserDao() {
		return userDao;
	}

	public void setUserDao(IUserDAO userDao) {
		this.userDao = userDao;
	}

	public void add(EditUserActionBean addUserActionBean)
			throws DBException {

		// 定义表对象
		User bean = new User();

		// 设置系统用户登录名
		bean.setUsername(addUserActionBean.getTxtUsername());
		// 初始密码设为：Const.PASSWORD
		bean.setPassword(Const.PASSWORD);
		userDao.save(bean);
	}
	public void delete(User user){
		try {
			userDao.delete(user);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}	
	}
	/**
	 * 删除系统用户
	 * 
	 * @return 删除信息
	 * @param noticeManaActionBean
	 */
//	public void delete(UserActionBean sysUserManaActionBean)
//			throws DBException {
//	}
	/**
	 * 检出是否有改用户登录名的用户
	 * @param bean
	 * @return
	 * @throws DBException
	 */
	public boolean checkExist(EditUserActionBean bean) throws DBException
	{
		  User temp=  userDao.findByLoginname(bean.getTxtUsername());		
		 if(null == temp)
			 return true;
		 else return false;
		
	}
	
	public User findUserById(long id) throws DBException
	{
		 User temp=  userDao.findUserById(id);				 
		 return temp;
	}


	public PageBean getUserList(UserActionBean sysUserManaActionBean)
			throws DBException {
		// 获取查询语句
		String hql = userDao.getAllHql();
		// 查询分页并返回
		PageBean pageBean = userDao.findByHqlPage(sysUserManaActionBean
				.getPageNum(), hql);
		// 返回分页结果
		return pageBean;
	}

	
	public String register(User user)
	{
		try {
			if (user == null) {
				return Message.SERVER_FAIL;
			}
			User temp=  userDao.findByLoginname(user.getUsername());	
			boolean flag = true;
			if(null == temp)
				 flag = true;
			 else  flag = false;
			if (flag) {
				userDao.save(user);
				long result = user.getId();
				if (result > 0) {
					return "" + result;
				} else {
					return Message.SERVER_FAIL;
				}
			} else {
				return Message.SERVER_USER_EXIST;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return Message.SERVER_USER_EXIST;
		}
		
	}

}
